/**
 * @File name: device.c
 * @Synopsis:
 * @Author: xing.dai@aliyun.com
 * @Version: 0.0.1
 * @Date: 2018-08-27 16:50
 */


#include "list.h"
#include "debug_print.h"
#include "os.h"
#include "os_api.h"
#include "static_pool.h"
#include "string.h"

static inline list_t *get_device_tree(void)
{
    return get_object_list(OBJECT_CLASS_DEVICE);
}

int device_register(device_t *device, char *name, uint32 flag)
{

    object_init(&(device->object), OBJECT_CLASS_DEVICE, name);
    device->flag = flag;
    device->count = 0;
    device->open_flag = 0;

    //dbg2("%s register complete.\n", device->object.name);
    return 0;
}

int device_tree_init(void)
{
    list_t *tree = get_device_tree();
    return list_init(tree);
}

device_t *device_find(const char *name)
{
    list_t   *tree = get_device_tree();
    node_t   *node;
    object_t *object;

    for (node = tree->head; node != NULL; node = node->next) {
        object = (object_t *)node;
        if (strncmp(object->name, name, OBJECT_NAME_MAX) == 0) {
            return (device_t *)object;
        }
    }
    return NULL;
}

int device_init(device_t *device)
{
    int res = 0;
    assert(device != NULL);

    if (device->init != NULL) {
        res = device->init(device);
    }
    return res;
}

int device_open(device_t *device, uint32 flag)
{
    int res = 0;
    assert(device != NULL);

    if (device->open != NULL) {
        res = device->open(device, flag);
    }
    return res;
}

int device_close(device_t *device)
{
    int res = 0;
    assert(device != NULL);

    if (device->close != NULL) {
        res = device->close(device);
    }
    return res;
}

uint32 device_read(device_t *device, int pos, void *buffer, uint32 size)
{
    assert(device != NULL);

    if (device->read != NULL) {
        return device->read(device, pos, buffer, size);
    }
    return 0;
}

uint32 device_write(device_t *device, int pos, void *buffer, uint32 size)
{
    assert(device != NULL);

    if (device->write != NULL) {
        return device->write(device, pos, buffer, size);
    }
    return 0;
}

int device_control(device_t *device, uint8 cmd, void *arg)
{
    assert(device != NULL);

    if (device->control != NULL) {
        return device->control(device, cmd, arg);
    }
    return 0;
}


